package com.contract.management.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.contract.management.bean.ReturnMessage;
import com.contract.management.bean.page.PageBean;
import com.contract.management.bean.page.PageResult;
import com.contract.management.bean.page.QueryBean;
import com.contract.management.bean.page.datatables.DtsPageResult;
import com.contract.management.bean.page.datatables.DtsParams;
import com.contract.management.domain.Bjd;
import com.contract.management.domain.CommJpaRepository;
import com.contract.management.domain.ContSmallClass;
import com.contract.management.domain.Department;
import com.contract.management.domain.SysConfig;
import com.contract.management.domain.User;
import com.contract.management.util.StrUtils;

@Controller
@RequestMapping("/system")
public class SystemController {

	@Autowired
	private CommJpaRepository repo;
	
	@RequestMapping(value = "/config", method = RequestMethod.GET)
	public String config() {
		return "sys_config";
	}
	
	@RequestMapping(value = "/config/edit", method = RequestMethod.POST)
	@ResponseBody
	public SysConfig editConfig(String id) {
		return repo.find(SysConfig.class, id);
	}
	
	@Transactional
	@RequestMapping(value = "/config/save", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage saveConfig(SysConfig config) {
		int num = repo.queryUpdate("update SysConfig set value = ?0 where key = ?1", config.getValue(), config.getKey());
		if(num == 0) return new ReturnMessage(false, "该参数不存在");
		return new ReturnMessage(true, "参数修改成功");
	}
	
	@RequestMapping("/config/list")
	@ResponseBody
	public List<Object[]> configList() {
		return repo.query("select describe, value, key from SysConfig where key = 'FZSH' or key = 'ZJLSH' order by sort");
	}
	
	@RequestMapping(value = "/bjd", method = RequestMethod.GET)
	public String bjd(Model model) {
		
		model.addAttribute("ywmcs", repo.query("select code, name from Config where type = 'ywlx'"));
		return "sys_bjd";
	}
	
	@RequestMapping(value = "/bjd/edit", method = RequestMethod.POST)
	@ResponseBody
	public Bjd editBjd(int id) {
		//return repo.queryOne("select new map(c.name as ywmc, b.smallType as smallType, b.bjje as bjje, b.id as id) from Bjd b, Config c where b.ywlx = c.code and b.id = ?0", id);
		return repo.find(Bjd.class, id);
	}
	
	@Transactional
	@RequestMapping(value = "/bjd/save", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage saveBjd(Bjd bjd) {
		if(bjd.getId() == null) {
			repo.persist(bjd);
		} else {
			Bjd b = repo.find(Bjd.class, bjd.getId());
			if(b == null) {
				return new ReturnMessage(false, "该参数不存在");
			} else {
				b.setYwlx(bjd.getYwlx());
				b.setSmallType(bjd.getSmallType());
				b.setBjje(bjd.getBjje());
				repo.merge(b);
			}
		}
		
		return new ReturnMessage(true, "参数修改成功");
	}
	
	@Transactional
	@RequestMapping(value = "/bjd/del", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage delBjd(int id) {
		repo.queryUpdate("delete Bjd where id = ?0", id);
		return new ReturnMessage(true, "报价单删除成功");
	}
	
	@RequestMapping("/bjd/list")
	@ResponseBody
	public List<Object[]> bjdList(String ywmc) {
		List<Object[]> list = null;
		if(StrUtils.isEmpty(ywmc)) {
			list = repo.query("select c.name, b.smallType, b.bjje, b.id from Bjd b, Config c where b.ywlx = c.code order by b.id");
		} else {
			list = repo.query("select c.name, b.smallType, b.bjje, b.id from Bjd b, Config c where b.ywlx = c.code and b.ywlx = ?0 order by b.id", ywmc);
		}
		return list;
	}
	
	@RequestMapping(value = "/dept", method = RequestMethod.GET)
	public String dept(Model model) {
		model.addAttribute("rights", repo.query("from Right"));
		return "sys_dept";
	}
	
	@RequestMapping(value = "/dept/edit", method = RequestMethod.POST)
	@ResponseBody
	public Department editDept(int id) {
		return repo.find(Department.class, id);
	}
	
	@Transactional
	@RequestMapping(value = "/dept/save", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage saveDept(Department dept) {
		if(dept.getRight() != null && dept.getRight().getId() == null) dept.setRight(null);
		
		if(dept.getId() == null) {
			Long num = repo.queryOne("select count(*) from Department where deptName = ?0", dept.getDeptName()); 
			if(num > 0) return new ReturnMessage(false, "该部门名称已经存在");
			repo.persist(dept);
		} else {
			Long num = repo.queryOne("select count(*) from Department where deptName = ?0 and id <> ?1", dept.getDeptName(), dept.getId()); 
			if(num > 0) return new ReturnMessage(false, "该部门名称已经存在");
			repo.merge(dept);
		}
		return new ReturnMessage(true);
	}
	
	@Transactional
	@RequestMapping(value = "/dept/del", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage delDept(int id) {
		repo.queryUpdate("update User set dept = null where dept.id = ?0", id);
		repo.queryUpdate("delete Department where id = ?0", id);
		return new ReturnMessage(true);
	}
	@RequestMapping("/dept/list")
	@ResponseBody
	public List<Object[]> deptList() {
		return repo.query("select d.deptName, r.name, d.id from Department d left join d.right r");
	}
	@RequestMapping("/dept/user/list")
	@ResponseBody
	public List<Object[]> deptUserList(Integer id) {
		if(id == null) return new ArrayList<>();
		return repo.query("select u.name, u.username, u.post, u.telephone from User u where u.dept.id = ?0", id);
	}
	
	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public String user(Model model) {
		model.addAttribute("depts", repo.query("select id, deptName from Department"));
		return "sys_user";
	}
	
	@RequestMapping("/user/list")
	@ResponseBody
	public DtsPageResult userList(DtsParams params) {
		String[] cols = new String[]{"id", "dept.deptName", "name", "username", "post", "telephone", "allowLogin"};
		String ql = "select obj.id, d.deptName, obj.name, obj.username, obj.post, obj.telephone, obj.allowLogin from User obj left join obj.dept d";
		String sumQl = "select count(*) from User obj";
		PageBean pb = params.createQuery(cols, ql, sumQl, (query) -> {
			List<QueryBean> ret = new ArrayList<>();
			for(Map.Entry<String, String> entry : query.entrySet()) {
				if(StrUtils.isEmpty(entry.getValue())) continue;
				String key = entry.getKey();
				if("dept".equals(key)) {
					ret.add(new QueryBean("dept.id", "=", Integer.valueOf(entry.getValue())));
				} else if("name".equals(key)) {
					ret.add(new QueryBean("name", "like", "%" + entry.getValue() + "%"));
				} else if("telephone".equals(key)) {
					ret.add(new QueryBean("telephone", "=", entry.getValue()));
				}
			}
			ret.add(new QueryBean("username", "!=", "admin"));
			return ret;
		});
		PageResult pr = repo.query(pb, params.getStart(), params.getLength());
		return new DtsPageResult(params.getDraw(), pr.getTotalCount(), pr.getData());
	}
	
	@Transactional
	@RequestMapping(value = "/user/save", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage saveUser(User user) {
		if(user.getDept() != null && user.getDept().getId() == null) user.setDept(null);
		
		if(user.getId() == null) {
			Long num = repo.queryOne("select count(*) from User where username = ?0", user.getUsername()); 
			if(num > 0) return new ReturnMessage(false, "该登录名已经存在");
			if(StrUtils.isEmpty(user.getPassword())) user.setPassword("123456");
			repo.persist(user);
		} else {
			Long num = repo.queryOne("select count(*) from User where username = ?0 and id <> ?1", user.getUsername(), user.getId()); 
			if(num > 0) return new ReturnMessage(false, "该登录名已经存在");
			if(StrUtils.isEmpty(user.getPassword())) {
				String password = repo.queryOne("select password from User where id = ?0", user.getId());
				user.setPassword(password);
			}
			repo.merge(user);
		}
		return new ReturnMessage(true);
	}
	@RequestMapping(value = "/user/edit", method = RequestMethod.POST)
	@ResponseBody
	public User editUser(int id) {
		User u = repo.find(User.class, id);
		u.setPassword("");
		return u;
	}
	
	@Transactional
	@RequestMapping(value = "/user/del", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage delUser(int id) {
		repo.queryUpdate("delete User where id = ?0", id);
		return new ReturnMessage(true);
	}
	
	@RequestMapping(value = "/zlqd", method = RequestMethod.GET)
	public String zlqd() {
		return "zlqd_list";
	}
	
	@RequestMapping("/zlqd/list")
	@ResponseBody
	public List<Object[]> zlqdList() {
		return repo.query("select s.id as id, concat((CASE s.bigClass.area WHEN 'A' THEN '上海' WHEN 'B' THEN '苏州' WHEN 'C' THEN '成都' END), '-',  s.bigClass.name, '-', s.name) as name, s.ht, s.zl from ContSmallClass s order by s.id");
	}
	
	@RequestMapping(value = "/zlqd/edit", method = RequestMethod.POST)
	@ResponseBody
	public ContSmallClass editZlqd(int id) {
		ContSmallClass c = repo.find(ContSmallClass.class, id);
		return c;
	}
	
	@Transactional
	@RequestMapping(value = "/zlqd/save", method = RequestMethod.POST)
	@ResponseBody
	public ReturnMessage saveZlqd(ContSmallClass cls) {
		ContSmallClass c = repo.find(ContSmallClass.class, cls.getId());
		if(c == null) {
			return new ReturnMessage(false, "该信息不存在");
		}
		c.setZl(cls.getZl());
		c.setHt(cls.getHt());
		repo.merge(c);
		
		return new ReturnMessage(true);
	}
}
